package cn.com.huzo.webapp.controller.master;

import cn.com.huzo.model.entities.master.MaterialCatalogueEntity;
import huzofw.common.web.controller.BaseFormController;
import cn.com.huzo.model.entities.master.MaterialEntity;
import cn.com.huzo.model.entities.master.MaterialGroupMemberMaterialEntity;
import cn.com.huzo.model.entities.master.MaterialPictureEntity;
import cn.com.huzo.service.master.MaterialCatalogueManager;
import cn.com.huzo.service.master.MaterialManager;
import cn.com.huzo.service.master.MaterialPictureManager;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import cn.com.huzo.service.master.MaterialGroupMemberMaterialManager;
import cn.com.huzo.service.master.MaterialSourceTypeManager;

/**
 * 材料信息控制器
 *
 * @author 吴旭
 */
@Controller
public class MaterialController extends BaseFormController {

    // <editor-fold defaultstate="collapsed" desc="属性">
    @Resource(name = "MaterialManager")
    private MaterialManager _manager;

    @Resource(name = "MaterialCatalogueManager")
    private MaterialCatalogueManager _manager_catalogue;

    @Resource(name = "MaterialPictureManager")
    private MaterialPictureManager _manager_picture;

    @Resource(name = "MaterialGroupMemberMaterialManager")
    private MaterialGroupMemberMaterialManager _manager_material_in_group;

    @Resource(name = "MaterialSourceTypeManager")
    private MaterialSourceTypeManager _manager_material_source_type;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="画面处理部分">
    /**
     * 跳转到材料一览画面
     * <p>
     * @param session
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("master/material/list.html")
    public ModelAndView redirectListWnd(HttpSession session) throws Exception {
        ModelAndView view = new ModelAndView();

        // 为画面设置变量
        view.setViewName("master.material.list.def");
        return view;
    }

    /**
     * 材料编辑画面
     * <p>
     * @param request 上下文请求
     * @param action 操作类别 1：增加 2：编辑
     * @param materialId 材料标识
     * @param nodeId 所属目录标识
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material/{action}/{materialId}/{nodeId}/edit.html",
            method = {RequestMethod.GET})
    public ModelAndView redirectEditWnd(HttpServletRequest request, @PathVariable(value = "action") int action,
            @PathVariable(value = "materialId") Long materialId,
            @PathVariable(value = "nodeId") Long nodeId) throws Exception {
        ModelAndView view = new ModelAndView();
        /*
        try {
            HttpServletRequest _request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (NullPointerException e) {
            // exception caught
        }*/

        String strImageUrl = "http://" + request.getServerName() // 服务器地址  
                + ":"
                + request.getServerPort() // 端口号  
                + "/erpimg";      // 项目名称  request.getContextPath()
        //+ request.getServletPath()      // 请求页面或其他地址  
        //+ "?" + (request.getQueryString()); // 参数   

        // 为画面设置变量
        view.addObject("MaterialSourceTypeList", _manager_material_source_type.fetchAll());  // 设置物料来源
        view.addObject("action", action);
        view.addObject("materialId", materialId);
        view.addObject("strImageUrl", strImageUrl);    // 设置图片显示路径

        if (nodeId != 0L) {
            MaterialCatalogueEntity _item = _manager_catalogue.fetchByKey(nodeId);
            view.addObject("nodeId", nodeId);
            view.addObject("nodeText", _item.getParentName() + " → " + _item.getCatalogueName());
        }

        view.setViewName("master.material.edit.def");
        return view;
    }

    /**
     * 弹出材料选择画面
     * <p>
     * @return
     */
    @RequestMapping("master/material/choice.html")
    public ModelAndView redirectChoiceWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.master.material.choice.def");
        return view;
    }

    /**
     * 弹出材料导入数据画面
     * <p>
     * @return
     */
    @RequestMapping("popup/master/material/import.html")
    public ModelAndView redirectImportMateriaPopupWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("/80_master/material_import");
        return view;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="导入数据处理部分">
    /**
     * 导入csv文件到数据库。
     * <p>
     * @param request
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "master/material/import.html",
            method = RequestMethod.POST,
            produces = {"application/xml", "application/json"})
    public @ResponseBody
    Map<String, ? extends Object> importMaterial(MultipartHttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap();

        //1. build an iterator
        Iterator<String> uploadFiles = request.getFileNames();
        if (!uploadFiles.hasNext()) {
            result.put("success", false);
            result.put("error", "没有上传文件。");
            return result;
        }
        MultipartFile mpf;

        String flag = request.getParameter("dir");
        Long userId = Long.parseLong(request.getParameter("userId"));
        String materialCategoryId = request.getParameter("materialCategoryId");
        String materialFlag = request.getParameter("materialFlag");
        String uploadDir = getServletContext().getRealPath("/upload/temp");

        // The following seems to happen when running jetty:run
        if (uploadDir == null) {
            String _newDir = request.getContextPath() + "/upload/temp";
            uploadDir = new File(_newDir).getAbsolutePath();
        }
        uploadDir += "/";
        // Create the directory if it doesn't exist
        File dirPath = new File(uploadDir);

        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }

        //2. get each file
        while (uploadFiles.hasNext()) {
            mpf = request.getFile(uploadFiles.next());
            String _fileName = "";
            // copy file to local disk (make sure the path "e.g. D:/temp/files" exists)            
            try {
                // 获得要上传文件的原始文件名 
                String fileName = mpf.getOriginalFilename();
                // 重命名文件 
                // 构建新的文件名上传到服务器上
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                // 新的文件名为 ：上传时间_原始文件名.xls 
                String newFileName = format.format(new Date()) + "_" + fileName;
                FileUtils.copyInputStreamToFile(mpf.getInputStream(), new File(uploadDir, newFileName));

                _fileName = uploadDir + newFileName;

                // 执行导入处理
                result = _manager.importDataFromCsv(_fileName, userId, Long.valueOf(materialCategoryId), materialFlag);

            } catch (IOException ex) {
                result.put("success", false);
                result.put("error", ex.getMessage());
            } finally {
                // 删除文件
                File file = new File(_fileName);
                if (file.exists()) {
                    file.delete();
                }
            }
        }

        return result;
    }

    // -------------------------------------------------------------------------
    // 导出数据处理部分
    // -------------------------------------------------------------------------
    /**
     * 弹出材料导出excel输出列选择画面
     * <p>
     * @return
     */
    @RequestMapping("popup/master/material/export/popupWnd.html")
    public ModelAndView redirectExportExcelWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popupWnd/80_master/materialExportExcelPopupWnd");
        return view;
    }

    /**
     * 得到全部材料表的字段列表
     *
     * @return 全部字段列表
     * @throws java.lang.Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "master/material/fetchAllFields.html",
            method = RequestMethod.POST,
            produces = {"application/xml", "application/json"})
    public @ResponseBody
    List<MaterialEntity> fetchAllFields() throws Exception {
        return _manager.fetchAllFields();
    }

    /**
     * 导出材料表到excel
     *
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "master/material/export.html",
            method = RequestMethod.POST)
    public ModelAndView exportViewExcelMaterial(HttpServletRequest request) throws Exception {
        Long Id = Long.parseLong(request.getParameter("_MaterialTypeId").trim());
        String materialtype = request.getParameter("_MaterialType").trim();
        //    JSONObject fieldslist = JSONObject.fromObject(request.getParameter("_FieldsList")); 
        String fieldslist = request.getParameter("_FieldsList");
        String commentlist = request.getParameter("_CommentList");
        String companyname = request.getParameter("_CompanyName");
        String materialcode = request.getParameter("_MaterialCode");
        String materialname = request.getParameter("_MaterialName");
        Map<String, Object> criterion = new HashMap();
        criterion.put("MaterialTypeId", Id);
        criterion.put("CompanyName", companyname);
        criterion.put("MaterialCode", materialcode);
        criterion.put("MaterialName", materialname);
        //     criterion.put("FieldsList", fieldslist); 

        String[] fieldsArr = fieldslist.split(",");
        List<String> lineslist = new ArrayList<>();
        //循环    
        for (Integer i = 0; i < fieldsArr.length; i++) {
            criterion.put("FieldName", fieldsArr[i]);
            List<String> linesdata = _manager.fetchExportData(criterion);
            //把list变成字符串
            String str = "";
            for (Integer j = 0; j < linesdata.size(); j++) {
                if (j == linesdata.size() - 1) {
                    str += linesdata.get(j);
                } else {
                    str += linesdata.get(j) + ",";
                }
            }
            lineslist.add(str);
        }
        //     List<MaterialEntity> lineslist= _manager.fetchAllByMaterialTypeId(criterion);
        Map<String, Object> model = new HashMap();
        model.put("lineslist", lineslist);
        model.put("materialtype", materialtype);
        model.put("commentlist", commentlist);
        return new ModelAndView("MaterialExcelView", model);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="主记录处理部分">
    /**
     * 根据标识取得材料数据。
     *
     * @param criterion 材料标识及当前用户
     * @return 材料数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material/fetchByKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchByHeaderKey(@RequestBody Map<String, Object> criterion) throws Exception {
        return _manager.fetchByHeaderKey(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "CurrentUserId"),
                MapUtils.getLong(criterion, "WorkFlowId"));
    }

    /**
     * 删除。
     *
     * @param criterion 要删除的数据
     * @return 返回删除后的数据
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> delete(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.delete(criterion);
    }

    /**
     * 根据条件取得材料信息分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 材料信息分页数据
     * @throws Exception
     */
    @RequestMapping(value = "master/material/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchForPage(@RequestBody Map<String, Object> criterion) throws Exception {
        return _manager.fetchForPage(criterion);
    }

    /**
     * 保存材料信息数据。
     * <p>
     * @param instance 要保存的材料信息对象。
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "master/material/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Long save(@RequestBody MaterialEntity instance) throws Exception {
        Long rowsAffected;

        if (instance.getMaterialId() != 0) { //编辑
            rowsAffected = (long) _manager.update(instance);
        } else {//新增
            rowsAffected = _manager.insert(instance);
        }

        return rowsAffected;
    }

    /**
     * 改变材料所属目录。
     *
     * @param itemList 要处理的数据列表
     * @return
     *
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material/changeCatalogue.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Integer changeCatalogue(@RequestBody final Map<String, ? extends List<MaterialEntity>> itemList) throws Exception {
        int rowsAffected = 0;

        if (itemList.get("updateList").size() > 0) {
            rowsAffected = _manager.batchChangeCatalogue(itemList.get("updateList"));
        }

        return rowsAffected;
    }

    /**
     * 审核材料数据。
     * <p>
     * @param criterion 要审核材料对象。
     * @return 影响行数.
     * @throws Exception
     */
    @RequestMapping(value = "master/material/check.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> check(@RequestBody Map<String, Object> criterion) throws Exception {
        return _manager.doCheck(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "WorkFlowId"),
                MapUtils.getShort(criterion, "NodeOrder"),
                MapUtils.getLong(criterion, "CheckedBy"),
                MapUtils.getShort(criterion, "IsCheckCurrentNode")
        );
    }

    /**
     * 反审材料数据。
     * <p>
     * @param criterion 要审核材料对象。
     * @return 影响行数.
     * @throws Exception
     */
    @RequestMapping(value = "master/material/uncheck.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> unCheck(@RequestBody Map<String, Object> criterion) throws Exception {
        return _manager.doUnCheck(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "WorkFlowId"),
                MapUtils.getShort(criterion, "NodeOrder"),
                MapUtils.getLong(criterion, "CheckedBy")
        );
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="材料图片处理部分">
    /**
     * 保存材料图片数据。
     * <p>
     * @param instance 要保存的材料图片对象。
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "master/material/picture/save.html",
            method = RequestMethod.POST,
            produces = {"application/json"})
    public @ResponseBody
    Map<String, Object> savePicture(@RequestBody MaterialPictureEntity instance) throws Exception {
        Map<String, Object> rtnValue = new HashMap();
        rtnValue.put("PictureId", _manager_picture.insert(instance));

        return rtnValue;
    }

    /**
     * 删除材料图片数据。
     *
     * @param instance 材料图片对象
     * @return 影响的行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material/picture/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Integer deletePicture(@RequestBody MaterialPictureEntity instance) throws Exception {
        return _manager_picture.delete(instance);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="材料分组处理部分">
    /**
     * 根据材料标识取得所在分组数据。
     *
     * @param materialKey 材料标识
     * @return 材料分组数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material_in_group/fetchGroupByMaterialKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<MaterialGroupMemberMaterialEntity> fetchGroupByMaterialKey(@RequestBody Long materialKey) throws Exception {
        return _manager_material_in_group.fetchByMaterialKey(materialKey);
    }

    /**
     * 从所在分组删除。
     *
     * @param criterion 材料在分组实例
     * @return 影响的行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material_in_group/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<MaterialGroupMemberMaterialEntity> deleteMaterialInGroup(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_material_in_group.deleteLines(
                MapUtils.getLong(criterion, "GroupId"),
                MapUtils.getString(criterion, "GroupName"),
                MapUtils.getLong(criterion, "MaterialId"),
                MapUtils.getString(criterion, "MaterialName"),
                MapUtils.getLong(criterion, "DeletedBy"));
    }

    /**
     * 设置材料所在分组。
     * <p>
     * @param itemList 要保存的数据。
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "master/material_in_group/insert.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> insertMaterialInGroup(@RequestBody final List<MaterialGroupMemberMaterialEntity> itemList) throws Exception {
        Map<String, Object> _result = new HashMap();
        if (itemList.isEmpty()) {
            _result.put("Success", false);
        } else {
            _result = _manager_material_in_group.batchInsert(itemList);
        }
        return _result;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="数据补全处理部分">
    /**
     * 根据输入的料从材料信息中补齐料号
     *
     * @param criterion 部分料号
     * @return 补全的料号列表
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "master/material/fetchMaterialCodeForAutoComplate.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<String> fetchMaterialCodeForAutoComplate(@RequestBody Map<String, Object> criterion) throws Exception {
        if (criterion.get("keyword") != null) {
            return _manager.fetchMaterialCodeForAutoComplate(MapUtils.getString(criterion, "keyword"));
        } else {
            return new ArrayList();
        }
    }
    // </editor-fold>
}
